package pers.qianyu.month_202012.date_20201218;

import java.util.*;

/**
 * 面试题 17.10. 主要元素
 * https://leetcode-cn.com/problems/find-majority-element-lcci/
 *
 * @author mizzle rain
 * @date 2020-12-18 21:09
 */
public class MajorityElement {
    // 哈希表计数
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }
        int mid = nums.length >> 1;
        int res = -1;
        for (Integer key : map.keySet()) {
            Integer value = map.get(key);
            if (value > mid) {
                res = key;
            }
        }
        return res;
    }

    // 摩尔投票法
    public int majorityElement2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        int count = 1;
        int key = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (count == 0) {
                key = nums[i];
            }
            if (nums[i] == key) {
                count++;
            } else {
                count--;
            }
        }
        if (isInvalid(nums, key)) {
            return -1;
        }
        return key;
    }

    private boolean isInvalid(int[] nums, int key) {
        int c = 0;
        for (int num : nums) {
            if (num == key) {
                c++;
            }
        }
        return c <= (nums.length >> 1);
    }
}
